import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography, Space } from 'antd';
import { UserOutlined, LockOutlined, PictureOutlined, ClusterOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { authApi } from '@/utils/api';
import { useAuth } from '@/contexts/AuthContext';
import { useServerConfig } from '@/contexts/ServerConfigContext';

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { login } = useAuth();
  const { serverConfig, updateHost, updatePort } = useServerConfig();

  const onFinish = async (values: { username: string; password: string; host: string; port: number }) => {
    setLoading(true);
    try {
      // 更新服务器配置
      updateHost(values.host);
      updatePort(values.port);

      const response = await authApi.login(
        { username: values.username, password: values.password },
        { host: values.host, port: values.port }
      );

      if (response.success && response.username && response.nickname) {
        message.success('登录成功');
        login({
          username: response.username,
          nickname: response.nickname
        });
        // 延迟跳转，确保状态更新完成
        setTimeout(() => {
          navigate('/dashboard');
        }, 100);
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error: any) {
      message.error(error.response?.data?.message || '网络错误，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Card className="login-box">
        <div className="login-header">
          <Space direction="vertical" size="small">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
              <PictureOutlined style={{ fontSize: '32px', color: '#667eea' }} />
              <Title level={2} style={{ margin: 0 }}>PicShare</Title>
            </div>
            <Text type="secondary">共享相册客户端</Text>
          </Space>
        </div>

        <Form
          name="login"
          onFinish={onFinish}
          layout="vertical"
          size="large"
          initialValues={{
            host: serverConfig.host,
            port: serverConfig.port
          }}
                  >
          <Form.Item
            label="服务器配置"
          >
            <div className="server-config-container">
              <div className="server-config-wrapper">
                <div className="server-host-input">
                  <Form.Item
                    name="host"
                    noStyle
                    rules={[{ required: true, message: '请输入服务器地址' }]}
                  >
                    <Input
                      prefix={<ClusterOutlined />}
                      placeholder="服务器地址"
                    />
                  </Form.Item>
                </div>
                <div className="server-port-input">
                  <Form.Item
                    name="port"
                    noStyle
                    rules={[{ required: true, message: '请输入端口号' }]}
                  >
                    <Input
                      type="number"
                      placeholder="端口"
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </Form.Item>

  
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入用户名"
            />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
            className="password-form-item"
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{ height: '48px', fontSize: '16px' }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;